package com.wxc.util;

import com.wxc.vo.Message;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wxc
 * @date 2021年10月02日 18:45
 */
@Slf4j
public class ConnectionUtil {
    private final Lock sendLock = new ReentrantLock();
    private final Lock receiveLock = new ReentrantLock();

    public <T> void send(Socket socket, Message<T> message) {
        if (socket.isOutputShutdown()) return;
        // log.debug("try get sendLock");
        sendLock.lock();
        // log.debug("try get sendLock success");
        try {
            send(socket.getOutputStream(), message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            sendLock.unlock();
            // log.debug("try to unlock sendLock success");
        }
    }

    private <T> void send(OutputStream outputStream, Message<T> message) {
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(outputStream);
            oos.writeObject(message);
        } catch (IOException e) {
            log.warn(e.getMessage());
        }
    }

    public <T> Message<T> receive(Socket socket) {
        if (socket.isInputShutdown()) return null;
        // log.debug("try get receiveLock");
        receiveLock.lock();
        // log.debug("try get receiveLock success");
        try {
            return receive(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            receiveLock.unlock();
            // log.debug("try to unlock receiveLock success");
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private <T> Message<T> receive(InputStream inputStream) {
        ObjectInputStream ois;
        Message<T> message = null;
        try {
            ois = new ObjectInputStream(inputStream);
            message = (Message<T>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.warn(e.getMessage());
        }
        return message;
    }

}
